<?php
namespace app\shop\model;
use app\BaseModel;
use app\card\model\Config;
use app\integral\model\IntegralGoods;
use app\member\model\Integral;
use app\member\model\Member;
use app\publics\model\TmplConfig;
use longbingcore\wxcore\WxTmpl;
use think\facade\Db;
use app\shop\model\AdminShopOrderGoods;



class AdminShopOrder extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_shop_order';
    protected static $company_id; #公司id/部门id
    protected static function init()
    {
        //TODO:初始化内容
    }
    protected $append = [
        'goods_text',
        'address_text',
        'staff_text',
        'company_text',
        'status_text',
        'hx_user_text',
        'hx_company_text',
        'nickname_text',
        'send_status_text'
    ];
    /**
     * @param $value
     * @param $data
     * @return mixed
     * 查询器 获取子订单
     */
    public function getGoodsTextAttr($value,$data)
    {
        $orer_goods      = new AdminShopOrderGoods();
        $dis['order_id'] = $data['id'];
        $order_goods     =  $orer_goods->orderGoodsInfo($dis);
        return transImagesOne($order_goods,['cover']);

    }

    /**
     * @param $value
     * @param $data
     * @return mixed
     * 查询器 拼接地址
     */
    public function getAddressTextAttr($value,$data)
    {

        $address_data = $data[ 'name' ] . '，'  . $data[ 'phone' ] . '，'  . $data[ 'address' ].'-'.$data[ 'address_detail' ];

        return $address_data;
    }

    /**
     * @param $value
     * @param $data
     * @return mixed
     * 查询器 员工信息
     */
    public function getStaffTextAttr($value,$data)
    {
        $staff_info = Db::name('longbing_card_user_info')->where(['fans_id'=>$data['to_uid']])->value('name');

        return !empty($staff_info)?$staff_info:'';
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/12 10:55
     * @功能说明: 获取用户公司/部门名称
     */
    public function getCompanyTextAttr($value,$data){
        return $this->getCompany($data['to_uid'],$data['uniacid']);
    }

    /**
     * @param $value
     * @param $data
     * @return mixed
     * 查询器 订单状态
     */
    public function getStatusTextAttr($value,$data)
    {
        if ( $data[ 'pay_status' ] == 0 ) {
            $text = '未支付';
            $text = $data['order_status']==1?$text.='-已取消':$text;

        } elseif($data[ 'pay_status' ] == 1) {
            if ($data['order_status'] == 0) {
                $text = '未发货';
                $text = $data['refund_status']==1?$text.='-退款中':$text;
                if($data['type'] == 1){
                    $text = '拼团中';
                    $collageInfo = Db::name('longbing_card_shop_collage_list')->where(['id' => $data['collage_id']])->value('collage_status');
                    if ($collageInfo == 2) {
                        $text = '拼团成功';
                    }else if($collageInfo == 3){
                        $text = '拼团完成';
                    }
                }
            }elseif($data['order_status'] == 1) {
                $text = '超时/取消';
            }elseif($data['order_status'] == 2) {
                $text = '已发货';
            }elseif($data['order_status'] == 3) {
                $text = '已完成';
            }elseif($data['order_status'] == 4) {
                $text = '已评价';
            }
        }else{
            $text = '已退款';
        }


        return $text;
    }
    /**
     * User: chenniang
     * Date: 2019-09-11 17:14
     * @param $value
     * @param $data
     * @return void
     * descption:自提|待发货状态
     */
    public function getSendStatusTextAttr($value,$data){
        $status = 0;
        if($data['pay_status']==1&&$data['order_status']==0&&($data['refund_status']==0||$data['refund_status']==3)){
            if ($data['type'] == 1) {
                $collageInfo = Db::name('longbing_card_shop_collage_list')->where(['id' => $data['collage_id']])->value('collage_status');
                if ($collageInfo == 2) {
                    $status = !empty($data['address_id'])&&$data['address_id']==-1?2:1;
                }
            }else{
                $status = !empty($data['address_id'])&&$data['address_id']==-1?2:1;

            }
        }
        return $status;
    }
    /**
     * @param $value
     * @param $data
     * @return mixed
     * 查询器 核销人
     */

    public function getHxUserTextAttr($value,$data){

        $hx_user_name = Db::name('longbing_card_user_info')->where(['fans_id' => $data[ 'write_off_id' ]] )->value('name');
        if(!$hx_user_name){
            $hx_user_name = Db::name('longbing_card_user')->where(['id' => $data[ 'write_off_id' ]] )->value('nickName');
        }

        return !empty($hx_user_name)?$hx_user_name:'';
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/12 10:55
     * @功能说明: 获取核销人公司/部门名称
     */
    public function getHxCompanyTextAttr($value,$data){
        if(!$data['write_off_id']){
            return null;
        }
        return $this->getCompany($data['write_off_id'],$data['uniacid']);
    }

    /**
     * @param $value
     * @param $data
     * @return mixed
     * 查询器 微信昵称
     */
    public function getNicknameTextAttr($value,$data){
        $username = Db::name('longbing_card_user')->where(['id' => $data[ 'user_id' ]] )->value('nickName');
        return $username;
    }
    /**
     * @param $dis
     * @param int $page
     * @return mixed
     * 获取订单列表
     */
    public function orderList($dis=array(),$page=10){
        $data = $this
            ->alias('a')
            ->Join('longbing_card_shop_order_item b' ,'a.id = b.order_id')
            ->leftJoin('longbing_card_user_info c' ,'a.to_uid = c.fans_id')
            ->where($dis)
            ->field(['a.*,b.id as order_goods_id'])
            ->order('a.id desc')
            ->group('a.id')
            ->paginate($page)
            ->toArray();
        return $data;
    }
    /**
     * @param $dis
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取所有订单列表
     */
    public function orderSelect($dis){
        $data = $this
            ->alias('a')
            ->Join('longbing_card_shop_order_item b' ,'a.id = b.order_id')
            ->leftJoin('longbing_card_user_info c' ,'a.to_uid = c.fans_id')
            ->where($dis)
            ->field(['a.*' ,'b.id as order_goods_id'])
            ->group('a.id')
            ->order('a.id desc')
            ->select()
            ->toArray();
        return $data;
    }
    /**
     * @param $dis
     * @param $data
     * @return int
     * 修改订单
     */

    public function orderUpdate($dis,$data){
        $data['update_time'] = time();
        $res = self::where($dis)->update($data);
        return $res;
    }

    /**
     * @param $dis
     * @return mixed
     * 获取订单详情
     */

    public function orderInfo($dis,$field='*'){
        $data = self::where($dis)->field($field)->find();
        return !empty($data)?$data->toArray():$data;
    }

    /**
     * @author chenniang
     * @DataTime: 2019-12-27 19:19
     * @功能说明:发送订阅消息
     */
    public function sendOrderService($order){
        //获取用户的open_id
        $user_model = new IndexUser();
        $openid     = $user_model->where(['id'=>$order['user_id']])->value('openid');
        //访问页面
        $page = 'shop/pages/order/detail?id='.$order['id'].'&target=user';
        //模版消息model
        $tmpl_model = new TmplConfig();
        //获取模版
        $tmpl       = $tmpl_model->where([['uniacid','=',$order['uniacid']],['tmpl_name','=','send_order'],['tmpl_id','<>',0]])->find();

        //如果未添加模版消息 则不发送
        if(empty($tmpl)){
            return true;
        }else{
            $tmpl = $tmpl->toArray();
        }
        //模版id
        $tmpl_id = $tmpl['tmpl_id'];
//        //模版类容
//        $key_worlds = $tmpl['kidList'];
        $service_model = new WxTmpl($order['uniacid']);
        //模版的key
        $key_worlds    = $service_model::getTmplKey($tmpl_id);

        if(!empty($openid)&&!empty($tmpl_id)&&!empty($key_worlds)){
            //验证模版内容
            if(!is_array($key_worlds)||count($key_worlds)<4){
                return true;
            }
            $order['express_company'] = $service_model::strToUtf8($order['express_company']);
            //发送内容
            $send_data = array(
                $key_worlds[1]=>array(
                    //发货时间物流公司
                    'value'=>date('Y-m-d H:i:s',$order['update_time']),
                ),
                $key_worlds[2]=>array(
                    //订单编号
                    'value'=>$order['out_trade_no'],
                ),
                $key_worlds[3]=>array(
                    //物流编号
                    'value'=>$order['courier_number'],
                ),
                $key_worlds[4]=>array(
                    //
                    'value'=>$order['express_company'],
                )
            );
            //模版消息库类
            $tmpl_sever = new WxTmpl($order['uniacid']);
            //发送模版消息
            $res = $tmpl_sever::sendTmpl($openid,$tmpl_id,$send_data,$page);
        }
        return true;
    }

    /**
     **@param $to_uid
     * @param $uniacid
     * @功能说明: 获取公司和部门
     * @author lichuanming
     * @DataTime: 2020/5/12 14:02
     */
    public function getCompany($to_uid,$uniacid){
        $Company = (new AdminCompany());
        $resData = array(
            'companyName'    => '未设置公司',
            'departmentName' => '未设置部门',
            'company_id' => '',
        );
        if(!$to_uid){
            return $resData;
        }

        $info = $Company->companyInfo($to_uid,$uniacid);
        if ( $info[ 'top_id' ] == 0 ){
            $resData['companyName'] = $info[ 'name' ];
            $resData['company_id']  = $info[ 'id' ];

        }else{
            $topCompany = $Company->getCompany( ['id'=>$info[ 'top_id' ]] );

            $companyName = '未设置公司';
            if ( $topCompany && $topCompany[ 'status' ] )
            {
                $companyName = $topCompany[ 'name' ];
            }
            list($resData['companyName'],$resData['departmentName'],$resData['company_id']) = array($companyName,$info[ 'name' ],$topCompany[ 'id' ]);
        }

        return $resData;
    }



    /**
     * User: chenniang
     * Date: 2019-09-12 18:37
     * @return bool
     * descption:检查订单
     */
    public function checkOrder($uniacid,$config){

        $this->checkOrderTime($uniacid,$config);

        $this->checkCollageTime($uniacid,$config);

        $this->checkSendTime($uniacid,$config);

        return true;
    }


    /**
     * User: chenniang
     * Date: 2019-09-12 14:43
     * @return void
     * descption: 检查超时订单
     */
    public function checkOrderTime($uniacid,$config){

        $order_overtime  = !empty($config['order_overtime'])?$config['order_overtime']:1800;

        $order_overtime  = time() - $order_overtime;

        $order_dis[] = ['uniacid','=',$uniacid];

        $order_dis[] = ['pay_status','=',0];

        $order_dis[] = ['order_status','<>',1];

        $order_dis[] = ['refund_status','=',0];

        $order_dis[] = ['create_time','<',$order_overtime];

        $order       = Db::name('longbing_card_shop_order')->where($order_dis)->field('id,record_id,collage_id,user_id,type,is_bargain')->select();

        if(!empty($order)){

            foreach ($order as $v){

                Db::startTrans();
                //修改订单状态
                $this->orderUpdate(['id'=>$v['id']],['order_status' => 1]);
                //归还优惠券
                if(!empty($v['record_id'])){

                    Db::name('longbing_card_coupon_record')->where(['id'=>$v['record_id']])->update(['status'=>1,'update_time'=>time()]);//恢复优惠券状态
                }
                //修改库存销量
                $res = $this->refundStock($v['id']);

                if($res!=1){

                    Db::rollback();

                    continue;
                }
                //拼团订单
                if($v['type']==1){

                    $user = Db::name('longbing_card_shop_collage_list')->where(['id'=>$v['collage_id']])->value('user_id');

                    Db::name('longbing_card_shop_user_collage')->where(['collage_id'=>$v['collage_id'],'user_id'=>$v['user_id']])->update(['collage_status'=>4]);

                    if($v['user_id']==$user){

                        Db::name('longbing_card_shop_collage_list')->where(['id'=>$v['collage_id']])->update(['status'=>4]);

                    }else{

                        Db::name('longbing_card_shop_collage_list')->where(['id'=>$v['collage_id']])->update(['left_number'=>Db::raw('left_number+1')]);
                    }
                }
                //砍价订单 如果超时需要改变砍价记录的状态
                if($v['is_bargain']==1){

                    $bargain_model = new BargainRecord();

                    $bargain_model->dataUpdate(['order_id'=>$v['id']],['status'=>4]);
                }

                Db::commit();
            }

        }

        return true;
    }


    /**
     * User: chenniang
     * Date: 2019-09-12 18:28
     * @return bool
     * descption:取消超时拼团
     */
    public function checkCollageTime($uniacid,$config){

        $water_model = new AdminSellingWater();

        $collage_overtime = !empty($config['collage_overtime'])?$config['collage_overtime']:3600;

        $collage_overtime = time() - $collage_overtime;

        $collage_status[] = ['collage_status','=',1];

        $collage_status[] = ['uniacid','=',$uniacid];

        $collage_status[] = ['create_time','<',$collage_overtime];

        $collage = Db::name('longbing_card_shop_collage_list')->where($collage_status)->select();

        Db::name('longbing_card_shop_collage_list')->where($collage_status)->update(['collage_status'=>4]);

        if(!empty($collage)){

            foreach ($collage as $value){

                $order = Db::name('longbing_card_shop_order')->where(['collage_id'=>$value['id'],'type'=>1])->field('id,order_status,pay_status')->select();

                Db::name('longbing_card_shop_user_collage')->where(['collage_id' => $value['id']])->update(['collage_status' => 4]);

                if(!empty($order)){

                    foreach ($order as $v){

                        $this->orderUpdate(['id'=>$v['id']],['order_status'=>1]);

                        if($v['pay_status']==1){

                            $water_model->refundWater(['order_id' => $v['id'], 'waiting'=>1]);
                        }
                    }
                }
            }
        }
        return true;
    }
    /**
     * User: chenniang
     * Date: 2019-09-12 18:28
     * @return bool
     * descption:自动收货
     */
    public function checkSendTime($uniacid,$config){

        $receiving = empty($config['receiving'])?5:$config['receiving'];

        $beginTime = time()-$receiving*86400;

        //$beginTime = $_SERVER['HTTP_HOST']=='longyiyi.migugu.com'?time()-120:time()-$receiving*86400;

        $dis[] = ['uniacid'      ,'=',$uniacid];

        $dis[] = ['pay_status'   ,'=',1];

        $dis[] = ['order_status' ,'=',2];

        $dis[] = ['refund_status','=',0];

        $dis[] = ['update_time'  ,'<',$beginTime];

        $list  = Db::name('longbing_card_shop_order')->where($dis)->select();

        if (!empty($list)) {

            foreach ( $list as $index => $item ) {

                Db::startTrans();

                $res = $this->orderUpdate(['id'=>$item['id']],['order_status'=>3]);

                if($res!=1){

                    Db::rollback();

                    continue;
                }

                $res = $this->profitUpdate($item);

                if($res!=true){

                    Db::rollback();

                    continue;
                }
                //会员模型
                $member_model = new Member();
                //结算会员的商品的权益
                $res = $member_model->updateMember($item);

                if($res!=true){

                    Db::rollback();

                    continue;
                }

                Db::commit();
            }

        }
        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-01-04 16:51
     * @功能说明:加库存减销量
     */
    public function refundStock($order_id){

        $spe_price_model =  new AdminShopSpePrice();

        $goods_model     = new AdminGoods();

        $i_goods_model   = new IntegralGoods();

        $memberi_model   = new Integral();

        $order_goods = Db::name('longbing_card_shop_order_item')->where(['order_id'=>$order_id])->select();

        foreach ($order_goods as $v){
            //查询该规格
            $spe = $spe_price_model->where(['id'=>$v['spe_price_id']])->find();

            if(!empty($spe)){

                $spe = $spe->toArray();
                //加库存
                $res = $spe_price_model->where(['id'=>$spe['id'],'create_time'=>$spe['create_time']])->update(['create_time'=>$spe['create_time']+1,'stock'=>$v['number']+$spe['stock']]);

                if($res!=1){

                    return $res;
                }
                //减销量
                $num = $v['number'];

                $res = $goods_model->goodsUpdate(['id'=>$v['goods_id']],['sale_count'=>Db::raw("sale_count-$num")]);

                if($res!=1){

                    return $res;

                }
                //退还积分库存 减去积分销量(积分商城)
                if(!empty($v['integral_goods_id'])){

                    $dis = [

                        'order_id' => $order_id,

                        'type'     => 3,

                        'order_goods_id' => $v['id']

                    ];

                    $memberi_model->where($dis)->update(['refund'=>1]);

                    $user_id = $this->where(['id'=>$order_id])->value('user_id');

                    $res = $memberi_model->integralUserAdd($user_id,$v['integral'],$v['uniacid'],1,5,$order_id,$v['integral_id'],$v['number'],1,$v['id'],$v['integral_goods_id']);

                    if($res==0){

                        return $res;

                    }

                }

            }

        }

        return 1;
    }


    /**
     * @param $order
     * @功能说明:
     * @author chenniang
     * @DataTime: 2021-01-04 17:47
     */
    public function profitUpdate($order){

        $water_model  = new AdminSellingWater();

        $profit_model = new AdminSellingProfit();

        $user_model   = new IndexUser();

        $list = $water_model->where(['order_id' => $order['id'], 'waiting' => 1])->select();

        if(!empty($list)){

            foreach ($list as $index => $item) {

                $money = $item['price'] * $item['extract'] / 100;

                if($item['selling_type']==1){

                    $money = $item[ 'extract_cash' ];
                }
                $money = sprintf("%.2f", $money);

                $profit= $profit_model->profitInfo(['user_id' => $item['user_id']]);

                if ($profit) {

                    if ($profit['waiting'] >= $money) {

                        $waiting      = $profit['waiting'] - $money;

                        $total_profit = $profit['total_profit'] + $money;

                        $profit_money = $profit['profit'] + $money;

                        $waiting      = sprintf("%.2f", $waiting);

                    } else {

                        $waiting      = 0;

                        $money        = $profit['waiting'];

                        $total_profit = $profit['total_profit'] + $profit['waiting'];

                        $profit_money = $profit['profit'] + $profit['waiting'];
                    }
                    $total_profit = sprintf("%.2f", $total_profit);

                    $profit_money = sprintf("%.2f", $profit_money);

                    $profit_model->profitUpdate(['id' => $profit['id']],['waiting' => $waiting, 'total_profit' => $total_profit, 'profit' => $profit_money]);

                    $user_model->userUpdate(['id' => $item['source_id']],['create_money'=>Db::raw("create_money+$money")]);
                }
            }
        }

        $res  = $water_model->waterUpdate(['order_id' => $order['id'], 'waiting' => 1],['waiting' => 2]);

        return true;
    }

}